<!-- vue3 <script setup> 版本 -->
<template>
  <el-dialog
    class="addorg-modal"
    v-model="visible"
    :title="data.title"
    :width="560"
    @close="onClose"
  >
    <el-form ref="formRef" :model="form" :rules="fromRules" :label-width="90">
      <el-form-item label="机构编号" prop="orgNo">
        <el-input v-model="form.orgNo" />
      </el-form-item>
      <el-form-item label="机构名称" prop="orgName">
        <el-input v-model="form.orgName" />
      </el-form-item>
      <el-form-item label="父机构" prop="parentId">
        <el-tree-select
          v-model="form.parentId"
          :data="treeSelectList"
          checkStrictly
          class="w-full"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="data.submitEvent(formRef)" :loading="state.loading"
          >确定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { ref, reactive, toRefs, watch, nextTick } from 'vue';
  import type { FormInstance } from 'element-plus';
  import { addOrg, updateOrg } from '/@/api/organization';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getOrgList } from '/@/api/organization';

  const state = reactive({
    loading: false,
  });
  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'update:visible', 'getParentId', 'getUpdateMode']);
  const props = defineProps({
    data: {
      type: Object || undefined,
      default: () => undefined,
    },
    visible: {
      type: Boolean,
      default: () => false,
    },
  });

  const data = reactive({
    title: '新建机构',
    updateMode: false,
    submitEvent: undefined as any,
  });

  const formRef = ref<FormInstance>();
  const form = reactive({
    id: undefined,
    orgNo: '',
    orgName: '',
    parentId: -1,
    remark: '',
    lockFlag: 0,
  });
  const fromRules = {
    orgNo: [{ required: true, message: '请输入机构编号', trigger: 'blur' }],
    orgName: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
  };

  const { data: defaultData, visible } = toRefs(props);

  const updateAction = (formRef) => {
    formRef.validate(async (v) => {
      if (v) {
        let params = { ...form };
        state.loading = true;
        let { code, msg } = await updateOrg(params);
        state.loading = false;
        if (code == 200) {
          createMessage({
            message: msg,
          });
          // 返回父级id
          emit('getParentId', form.parentId);
          // 返回弹框类型
          emit('getUpdateMode', data.updateMode);
          emit('update:visible', false);
          emit('success');
        }
      }
    });
  };
  const createAction = (formRef) => {
    formRef.validate(async (v) => {
      if (v) {
        let params = { ...form };
        delete params.id;
        state.loading = true;
        let { code, msg } = await addOrg(params);
        state.loading = false;
        if (code == 200) {
          createMessage({
            message: msg,
          });
          emit('getParentId', form.parentId);
          emit('getUpdateMode', data.updateMode);
          emit('update:visible', false);
          emit('success');
        }
      }
    });
  };
  data.submitEvent = createAction;

  watch(visible, (nv: boolean) => {
    if (nv) {
      getOrgListReq(props.data?.id || null);
      data.updateMode = props.data?.id ? true : false;
      data.title = data.updateMode ? '编辑机构' : '新建机构';
      data.submitEvent = data.updateMode ? updateAction : createAction;
      if (data.updateMode) {
        nextTick(() => {
          form.id = defaultData?.value?.id;
          form.orgNo = defaultData?.value?.orgNo;
          form.orgName = defaultData?.value?.orgName;
          form.remark = defaultData?.value?.remark;
          form.lockFlag = defaultData?.value?.lockFlag;
          form.parentId = defaultData?.value?.parentId;
        });
      }
    }
  });
  function treeSelectTransform(s, orgId) {
    if (!s || !s.length) return [];
    let t = [] as any;
    for (let k in s) {
      if (s[k].id == orgId) continue;
      t.push({
        label: s[k].orgName,
        value: s[k].id,
        children: treeSelectTransform(s[k].children, orgId),
        clientModel: s[k].clientModel,
      });
    }
    return t;
  }
  let treeSelectList = ref([]);

  const onClose = () => {
    formRef.value?.resetFields();
    emit('update:visible', false);
  };

  const getOrgListReq = async (orgId) => {
    let { data: ret, code } = await getOrgList({});
    state.loading = false;
    treeSelectList.value = [];
    if (code === 200) {
      let result = ret ? treeSelectTransform(ret, orgId) : [];
      result.unshift({ label: '无', value: '-1' });
      treeSelectList.value = result;
    }
  };
</script>

<style lang="less">
  .addorg-modal {
    .ant-modal-body {
      padding: 20px;
    }
  }
</style>
